import React, { useContext, useReducer } from 'react'
import { useSelector } from 'react-redux'

import { reducers, defaultState } from '../store/reducers'
import { MyContext } from '../store/store'
import { changeCount, changeCity, changeTest, changeList } from '../store/actions'
import axios from 'axios'
import { styles } from '../utils'

function useStore() {
  const { state, dispatch } = useContext(MyContext)
  return {
    state,
    dispatch
  }
}


const MyRedux = () => {
  const [state, dispatch] = useReducer(reducers, defaultState)
  return (
    <div>
      <MyContext.Provider value={{ state, dispatch }}>
        <MainBox></MainBox>
      </MyContext.Provider>
    </div>
  )
}

const MainBox = () => {
  return (
    <div style={styles.box}>
      <h2>MainBox - 1</h2>
      <hr />
      <ChildOne></ChildOne>
      <hr />
      <ChildTwo></ChildTwo>
    </div>
  )
}

const ChildOne = () => {
  const { state } = useContext(MyContext)
  const { count, city, test, list } = state
  return (
    <div style={styles.box}>
      <h2>ChildOne - 子组件</h2>
      <h3>count = {count}</h3>
      <h3>city = {city}</h3>
      <h3>test = {test}</h3>
      <ul>
        {
          list.map(item => {
            return (
              <li key={item._id}>{item.name}</li>
            )
          })
        }
      </ul>
    </div>
  )
}

const ChildTwo = () => {
  const { dispatch, state } = useStore()

  const getTest = async () => {
    const res = await axios.get('http://81.69.235.62:3000/api/test')
    dispatch(changeTest(res.data.msg))
  }

  const getList = async () => {
    const res = await axios.get('http://81.69.235.62:3000/api/goodlist')
    dispatch(changeList(res.data.result))
  }


  return (
    <div style={styles.box}>
      <h2>ChildTwo - 子组件</h2>
      <button className='learn-more' onClick={() => dispatch(changeCount(10))}>change count</button>
      <button className='learn-more' onClick={() => dispatch(changeCity('上海'))}>change city</button>
      <button className='learn-more' onClick={getTest}>change test</button>
      <button className='learn-more' onClick={getList}>change list</button>
      <button className='learn-more' onClick={() => dispatch(changeList([]))}>cls list</button>
    </div>
  )
}

export default MyRedux
